package apps.sim;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.JWindow;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class Splash extends JWindow {
	private Image image;
	private int left;
	private int top;
	private int width;
	private int height;

	public Splash(String imageFileName) {
		super(new Frame());
		this.setAlwaysOnTop(true);
		try {
			Toolkit toolkit = Toolkit.getDefaultToolkit();

			URL imageUrl = getClass().getResource(imageFileName);
			image = toolkit.getImage(imageUrl);

			MediaTracker mediaTracker = new MediaTracker(this);
			mediaTracker.addImage(image, 0);
			mediaTracker.waitForID(0);

			width = image.getWidth(this);
			height = image.getHeight(this);

			Dimension screenSize = toolkit.getScreenSize();

			left = (screenSize.width - width) / 2;
			top = (screenSize.height - height) / 2;
		} catch (Exception exception) {
			exception.printStackTrace();
			image = null;
		}
	}

	public void open(int nMilliseconds) {
		if (image == null)
			return;

		Timer timer = new Timer(Integer.MAX_VALUE, new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				((Timer) event.getSource()).stop();
				close();
			};
		});

		timer.setInitialDelay(nMilliseconds);
		timer.start();

		setBounds(left, top, width, height);
		setVisible(true);
	}

	public void close() {
		setVisible(false);
		dispose();
	}

	public void paint(Graphics graphics) {
		if (image == null)
			return;
		graphics.drawImage(image, 0, 0, width, height, this);
	}
}
